// 全局变量
let refreshInterval;
let isAutoRefresh = true;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadOnlineUsers();
    setupAutoRefresh();
});

// 设置自动刷新
function setupAutoRefresh() {
    const autoRefreshCheckbox = document.getElementById('auto-refresh');
    if (autoRefreshCheckbox) {
        autoRefreshCheckbox.addEventListener('change', function() {
            isAutoRefresh = this.checked;
            if (isAutoRefresh) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });
    }
    
    if (isAutoRefresh) {
        startAutoRefresh();
    }
}

// 加载在线用户数据
async function loadOnlineUsers() {
    try {
        const response = await fetch('/api/online-users');
        const users = await response.json();
        
        if (response.ok) {
            updateOnlineUsersTable(users);
            updateTrafficStats(users);
            updateUserCount(users.length);
        } else {
            console.error('加载数据失败:', users.error);
            showTableError('加载数据失败: ' + users.error);
        }
    } catch (error) {
        console.error('网络错误:', error);
        showTableError('网络连接错误，请检查服务器状态');
    }
}

// 更新在线用户表格
function updateOnlineUsersTable(users) {
    const tbody = document.getElementById('online-users-table');
    
    if (users.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="empty-state">
                    <i class="fas fa-users-slash"></i>
                    <h3>暂无在线用户</h3>
                    <p>当前没有用户连接到OpenVPN服务器</p>
                </td>
            </tr>
        `;
        return;
    }
    
    const rowsHTML = users.map(user => createTableRow(user)).join('');
    tbody.innerHTML = rowsHTML;
}

// 创建表格行
function createTableRow(user) {
    // 调试输出
    console.log('创建表格行，用户数据:', {
        username: user.username,
        virtual_address: user.virtual_address,
        location: user.location,
        traffic_received: user.traffic_received,
        traffic_sent: user.traffic_sent,
        duration: user.duration,
        connected_since: user.connected_since,
        last_updated: user.last_updated
    });
    
    const connectedTime = user.connected_since ? new Date(user.connected_since).toLocaleString('zh-CN') : '未知';
    const lastUpdated = user.last_updated ? new Date(user.last_updated).toLocaleString('zh-CN') : '未知';
    const location = user.location || '未知地区';
    
    return `
        <tr>
            <td>
                <div class="user-cell">
                    <div class="user-avatar-small">
                        ${user.username.charAt(0).toUpperCase()}
                    </div>
                    <span class="username">${user.username}</span>
                </div>
            </td>
            <td><code class="ip-address">${user.virtual_address}</code></td>
            <td class="location-cell">
                <i class="fas fa-map-marker-alt"></i>
                <span class="location-text">${location}</span>
            </td>
            <td class="traffic-cell download">
                <i class="fas fa-download"></i>
                ${user.traffic_received}
            </td>
            <td class="traffic-cell upload">
                <i class="fas fa-upload"></i>
                ${user.traffic_sent}
            </td>
            <td class="duration-cell" data-connected-since="${user.connected_since}">
                <i class="fas fa-clock"></i>
                <span class="duration-text">${user.duration}</span>
            </td>
            <td class="time-cell">${connectedTime}</td>
            <td class="time-cell">${lastUpdated}</td>
        </tr>
    `;
}

// 更新流量统计
function updateTrafficStats(users) {
    let totalReceived = 0;
    let totalSent = 0;
    
    users.forEach(user => {
        totalReceived += user.bytes_received || 0;
        totalSent += user.bytes_sent || 0;
    });
    
    const totalTraffic = totalReceived + totalSent;
    
    document.getElementById('total-received').textContent = formatBytes(totalReceived);
    document.getElementById('total-sent').textContent = formatBytes(totalSent);
    document.getElementById('total-traffic').textContent = formatBytes(totalTraffic);
}

// 更新用户计数
function updateUserCount(count) {
    const countElement = document.getElementById('user-count');
    if (countElement) {
        countElement.textContent = `${count} 个用户在线`;
    }
}

// 刷新在线用户数据
function refreshOnlineUsers() {
    loadOnlineUsers();
    
    // 添加刷新动画
    const refreshBtn = document.querySelector('.refresh-btn');
    const icon = refreshBtn.querySelector('i');
    icon.classList.add('fa-spin');
    
    setTimeout(() => {
        icon.classList.remove('fa-spin');
    }, 1000);
}



// 显示通知消息
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <div class="notification-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
        <button class="notification-close" onclick="this.parentElement.remove()">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 自动移除通知
    setTimeout(() => {
        if (notification.parentElement) {
            notification.remove();
        }
    }, 5000);
}

// 开始自动刷新
function startAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    if (isAutoRefresh) {
        refreshInterval = setInterval(() => {
            loadOnlineUsers();
        }, 30000); // 30秒刷新一次
        
        // 添加实时更新在线时长的定时器
        setInterval(() => {
            updateDurations();
        }, 1000); // 每秒更新一次在线时长
    }
}

// 实时更新在线时长
function updateDurations() {
    const durationCells = document.querySelectorAll('.duration-cell[data-connected-since]');
    
    durationCells.forEach(cell => {
        const connectedSince = cell.getAttribute('data-connected-since');
        const durationText = cell.querySelector('.duration-text');
        
        if (connectedSince && durationText) {
            try {
                // 尝试解析连接时间
                const connectedTime = new Date(connectedSince);
                if (!isNaN(connectedTime.getTime())) {
                    const now = new Date();
                    const duration = now - connectedTime;
                    const totalSeconds = Math.floor(duration / 1000);
                    
                    // 格式化显示时长
                    const hours = Math.floor(totalSeconds / 3600);
                    const minutes = Math.floor((totalSeconds % 3600) / 60);
                    const seconds = totalSeconds % 60;
                    
                    let durationStr;
                    if (hours > 0) {
                        durationStr = `${hours}小时${minutes}分钟${seconds}秒`;
                    } else if (minutes > 0) {
                        durationStr = `${minutes}分钟${seconds}秒`;
                    } else {
                        durationStr = `${seconds}秒`;
                    }
                    
                    durationText.textContent = durationStr;
                }
            } catch (e) {
                console.warn('更新在线时长失败:', e);
            }
        }
    });
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
    }
}

// 格式化字节数
function formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示表格错误信息
function showTableError(message) {
    const tbody = document.getElementById('online-users-table');
    tbody.innerHTML = `
        <tr>
            <td colspan="8" class="error-state">
                <i class="fas fa-exclamation-triangle"></i>
                <h3>加载失败</h3>
                <p>${message}</p>
                <button class="refresh-btn" onclick="refreshOnlineUsers()">
                    <i class="fas fa-sync-alt"></i> 重试
                </button>
            </td>
        </tr>
    `;
}

// 页面卸载时清理定时器
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});

// 页面可见性变化时处理自动刷新
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        stopAutoRefresh();
    } else {
        if (isAutoRefresh) {
            startAutoRefresh();
        }
    }
});

// 添加额外的CSS样式
const additionalStyles = `
    .data-table .user-cell {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .data-table .user-avatar-small {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 14px;
        font-weight: 600;
        flex-shrink: 0;
    }
    
    .data-table .username {
        font-weight: 600;
        color: #2d3748;
    }
    
    .data-table .ip-address {
        background: rgba(102, 126, 234, 0.1);
        padding: 4px 8px;
        border-radius: 6px;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        color: #667eea;
        white-space: nowrap;
    }
    
    .data-table .traffic-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 600;
        white-space: nowrap;
    }
    
    .data-table .traffic-cell.download {
        color: #38a169;
    }
    
    .data-table .traffic-cell.upload {
        color: #dd6b20;
    }
    
    .data-table .duration-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #667eea;
        font-weight: 600;
        white-space: nowrap;
    }
    
    .data-table .time-cell {
        white-space: nowrap;
        font-size: 12px;
        color: #718096;
    }
    
    .data-table .location-cell {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #805ad5;
        font-weight: 600;
        white-space: nowrap;
    }
    
    .data-table .location-text {
        font-size: 12px;
    }
    

    
    .empty-state, .error-state {
        text-align: center;
        padding: 40px;
        color: #718096;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 15px;
    }
    
    .empty-state i, .error-state i {
        font-size: 24px;
        color: #667eea;
    }
    
    .empty-state h3, .error-state h3 {
        color: #2d3748;
        margin: 0;
    }
    
    .empty-state p, .error-state p {
        margin: 0;
        color: #718096;
    }
    
    .notification {
        position: fixed;
        top: 20px;
        right: 20px;
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        padding: 16px 20px;
        display: flex;
        align-items: center;
        gap: 12px;
        z-index: 1000;
        min-width: 300px;
        max-width: 400px;
        animation: slideInRight 0.3s ease;
    }
    
    .notification-success {
        border-left: 4px solid #38a169;
    }
    
    .notification-error {
        border-left: 4px solid #e53e3e;
    }
    
    .notification-info {
        border-left: 4px solid #3182ce;
    }
    
    .notification-content {
        display: flex;
        align-items: center;
        gap: 10px;
        flex: 1;
    }
    
    .notification-content i {
        font-size: 18px;
    }
    
    .notification-success .notification-content i {
        color: #38a169;
    }
    
    .notification-error .notification-content i {
        color: #e53e3e;
    }
    
    .notification-info .notification-content i {
        color: #3182ce;
    }
    
    .notification-close {
        background: none;
        border: none;
        color: #718096;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        transition: all 0.2s ease;
    }
    
    .notification-close:hover {
        background: #f7fafc;
        color: #2d3748;
    }
    
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
`;

// 动态添加样式
const styleSheet = document.createElement('style');
styleSheet.textContent = additionalStyles;
document.head.appendChild(styleSheet); 